package library

import (
	"encoding/json"
	"fmt"

	"chat.com/model"
	"chat.com/pkg/cache"
)

// 获取用户在线数据
func GetUserOnlineInfo(userKey string) (userOnline *model.UserOnline, err error) {
	key := GenUserOnlineKey(userKey)
	data, err := cache.Rdb.Get(key)
	if err != nil {
		if err == cache.Nil {
			fmt.Println("GetUserOnlineInfo", userKey, err)
			return
		}

		fmt.Println("GetUserOnlineInfo", userKey, err)
		return
	}

	userOnline = &model.UserOnline{}
	err = json.Unmarshal([]byte(data), userOnline)
	if err != nil {
		fmt.Println("获取用户在线数据 json Unmarshal", userKey, err)
		return
	}

	fmt.Println(
		"获取用户在线数据", userKey, "time", userOnline.LoginTime, userOnline.HeartbeatTime, "AccIp",
		userOnline.AccServerAddr, userOnline.RpcServerAddr, userOnline.IsLogoff)

	return
}

// 设置用户在线数据
func SetUserOnlineInfo(userKey string, userOnline *model.UserOnline) (err error) {
	key := GenUserOnlineKey(userKey)
	valueByte, err := json.Marshal(userOnline)
	if err != nil {
		fmt.Println("设置用户在线数据 json Marshal", key, err)
		return
	}

	err = cache.Rdb.Set(key, string(valueByte), UserOnlineCacheTime)
	if err != nil {
		fmt.Println("设置用户在线数据 ", key, err)
		return
	}

	return
}
